package com.zisuyi.game.sdk.game

import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.weilele.mvvm.base.helper.ILifecycleObserver
import com.weilele.mvvm.utils.activity.toast
import com.yizisu.library.ad.IAd
import com.zisuyi.game.sdk.game.bean.AndroidJsBean
import org.egret.egretnativeandroid.EgretNativeAndroid

class GameEgret(val appCompatActivity: AppCompatActivity) :
        EgretNativeAndroid(appCompatActivity),
        ILifecycleObserver {
    companion object {
        private const val TAG = "GameEgret"
        private const val MESSAGE_FROM_JS = "sendToJS"
        const val MESSAGE_SEND_TO_JS = "sendToNative"
    }

    val gameReceiveMessage = GameReceiveMessage(this)

    /**
     * 让外部创建
     */
    var gameAd: IAd? = null

    init {
        appCompatActivity.lifecycle.addObserver(this)
        initGameEgret()
    }

    private fun initGameEgret() {
        val nativeAndroid = this
        if (!nativeAndroid.checkGlEsVersion()) {
            "This device does not support OpenGL ES 2.0.".toast()
            return
        }
        nativeAndroid.config.showFPS = false
        nativeAndroid.config.fpsLogTime = 30
        nativeAndroid.config.disableNativeRender = false
        nativeAndroid.config.clearCache = false
        nativeAndroid.config.loadingTimeout = 0
        nativeAndroid.config.immersiveMode = true
        nativeAndroid.config.useCutout = true
        setExternalInterfaces()
        if (!nativeAndroid.initialize("file:///android_asset/game/index.html")) {
            "Initialize native failed.".toast()
        }
    }

    override fun onCreate() {
        super.onCreate()
        gameReceiveMessage.onCreate()
    }

    override fun onDestroy() {
        super.onDestroy()
        gameReceiveMessage.onDestroy()
    }

    override fun onPause() {
        super.onPause()
        pause()
    }

    override fun onResume() {
        super.onResume()
        resume()
    }

    var onBackListener: Function1<GameEgret, Unit>? = null
    internal fun onBackPressed() {
        if (onBackListener == null) {
            finishGame()
        } else {
            onBackListener?.invoke(this)
        }
    }

    fun finishGame() {
        exitGame()
        appCompatActivity.finish()
    }

    private fun setExternalInterfaces() {
        setExternalInterface(MESSAGE_FROM_JS) { message ->
            Log.d(TAG, "Get message: $message")
            gameReceiveMessage.distributeMessages(message)
        }
        setExternalInterface("@onState") { message ->
            Log.e(TAG, "Get @onState: $message")
        }
        setExternalInterface("@onError") { message ->
            Log.e(TAG, "Get @onError: $message")
        }
        setExternalInterface("@onJSError") { message ->
            Log.e(TAG, "Get @onJSError: $message")
        }
    }
}